<!-- templates/customer_service/ai_service.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能客服 - 二手交易平台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary-brown: #f26552;
            --secondary-brown: #f26552;
            --light-brown: #D7CCC8;
            --bg-beige: #EFEBE9;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Quicksand', sans-serif;
        }

        body {
            background: url('https://pic2.zhimg.com/v2-86ffa1ad12c00587d5cb6f9bd362578a_r.jpg?source=1940ef5c') no-repeat center center fixed;
            height: 100vh;
            display: flex;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 120px;
            background: var(--primary-brown);
            padding: 30px 15px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 30px;
        }

        .nav-btn {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background: var(--secondary-brown);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: 0.3s;
            color: white;
            text-align: center;
            font-size: 0.9em;
        }

        .nav-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        }

        .nav-btn i {
            font-size: 1.5em;
            margin-bottom: 5px;
        }

        /* 聊天区样式 */
        .chat-container {
            flex: 1;
            margin: 20px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
        }

        .chat-header {
            padding: 20px;
            background: var(--primary-brown);
            border-radius: 15px 15px 0 0;
            color: white;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .chat-history {
            flex: 1;
            padding: 25px;
            overflow-y: auto;
            background: linear-gradient(to bottom, #FFF8F5, #FFFAF8);
        }

        .message {
            margin: 15px 0;
            display: flex;
            gap: 15px;
        }

        .bot-message .message-content {
            background: var(--light-brown);
            border-radius: 0 20px 20px 20px;
            padding: 15px 20px;
            max-width: 70%;
        }

        .user-message {
            justify-content: flex-end;
        }

        .user-message .message-content {
            background: var(--secondary-brown);
            color: white;
            border-radius: 20px 0 20px 20px;
            padding: 15px 20px;
            max-width: 70%;
        }

        .input-container {
            padding: 20px;
            border-top: 2px solid var(--light-brown);
            display: flex;
            gap: 15px;
        }

        .input-box {
            flex: 1;
            position: relative;
        }

        input[type="text"] {
            width: 100%;
            padding: 15px 60px 15px 25px;
            border: 2px solid var(--light-brown);
            border-radius: 30px;
            font-size: 16px;
            transition: 0.3s;
        }

        input[type="text"]:focus {
            border-color: var(--primary-brown);
            outline: none;
        }

        .camera-btn {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary-brown);
            cursor: pointer;
            font-size: 1.2em;
        }

        .send-btn {
            background: var(--primary-brown);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 30px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: 0.3s;
        }

        .send-btn:hover {
            background: var(--secondary-brown);
        }

        .loading {
            display: none;
            text-align: center;
            color: var(--primary-brown);
            padding: 10px;
        }

        /* 评价按钮样式 */
        .rating-btn {
            margin: 5px;
            padding: 10px;
            border: none;
            border-radius: 5px;
            background-color: #f0f0f0;
            cursor: pointer;
        }
        .rating-btn:hover {
            background-color: #ddd;
        }

    </style>
</head>
<body>
    {% csrf_token %}
    <!-- 侧边栏 -->
    <nav class="sidebar">
        <div class="nav-btn" onclick="showRating()">
            <i class="fas fa-star"></i>
            客服评价
        </div>
        <div class="nav-btn" onclick="queryOrder()">
            <i class="fas fa-search"></i>
            订单查询
        </div>
        <div class="nav-btn" onclick="connectHuman()">
            <i class="fas fa-headset"></i>
            人工客服
        </div>
        <div class="nav-btn" onclick="afterService()">
            <i class="fas fa-shield-alt"></i>
            售后服务
        </div>
    </nav>

    <!-- 聊天区 -->
    <main class="chat-container">
        <header class="chat-header">
            <i class="fas fa-robot"></i>
            <h1>小智助手</h1>
        </header>

        <div class="chat-history" id="chatHistory">
            <div class="message bot-message">
                <div class="message-content">
                    您好！我是二手交易平台智能助手--小智，可以为您：
                    <ul style="margin-top: 10px; padding-left: 20px;">
                        <li>查询订单状态</li>
                        <li>解答交易问题</li>
                        <li>识别商品照片</li>
                        <li>处理售后服务</li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="loading" id="loading">
            <i class="fas fa-spinner fa-spin"></i> 正在思考中...
        </div>

        <div class="input-container">
            <div class="input-box">
                <input type="text" id="userInput" placeholder="输入您的问题或需求...">
                <label for="fileInput" class="camera-btn">
                    <i class="fas fa-camera"></i>
                </label>
                <input type="file" id="fileInput" accept="image/*" hidden>
            </div>
            <button class="send-btn" onclick="sendMessage()">
                <i class="fas fa-paper-plane"></i>
                发送
            </button>
        </div>
    </main>

    <script>
        // 消息处理逻辑
        const chatHistory = document.getElementById('chatHistory');
        const userInput = document.getElementById('userInput');
        const loading = document.getElementById('loading');
        const fileInput = document.getElementById('fileInput');

        // 自动滚动到底部
        function scrollToBottom() {
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }

        // 添加消息
        function addMessage(content, isUser = false, isImage = false) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`;

            let contentHtml = isImage
                ? `<img src="${content}" style="max-width: 300px; border-radius: 15px;">`
                : content;

            messageDiv.innerHTML = `
                <div class="message-content">${contentHtml}</div>
            `;
            chatHistory.appendChild(messageDiv);
            scrollToBottom();
        }

        // 图片处理
        fileInput.addEventListener('change', async function(e) {
            const file = e.target.files[0];
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    addMessage(event.target.result, true, true);
                };
                reader.readAsDataURL(file);

                loading.style.display = 'block';

                try {
                    const formData = new FormData();
                    formData.append('image', file);
                    formData.append('csrfmiddlewaretoken', document.querySelector('[name=csrfmiddlewaretoken]').value);

                    const response = await fetch('/api/image-recognize/', {
                        method: 'POST',
                        body: formData
                    });

                    const data = await response.json();
                    if(data.success) {
                        let message = `识别结果：${data.item_name}<br>推荐商品：`;
                        message += data.recommendations.map(item =>
                            `• ${item.name}（￥${item.price}）`
                        ).join('<br>');
                        addMessage(message);
                    } else {
                        addMessage('未能识别商品，请尝试更清晰的图片');
                    }
                } catch (error) {
                    addMessage('图片识别服务暂时不可用');
                }
                loading.style.display = 'none';
            }
        })


        // 发送消息（优化版）
        async function sendMessage() {
            const input = document.getElementById('userInput');
            const message = input.value.trim();
            if (!message) return;

            const loading = document.getElementById('loading');
            loading.style.display = 'block';
            input.value = ''; // 清空输入框

            try {
                // 显示用户消息
                addMessage(message, true);

                // 获取 CSRF Token
                const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;

                // 发送请求
                const response = await fetch('/user/question/', {  // 确保路径正确
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': csrfToken
                    },
                    body: JSON.stringify({ message: message })
                });

                const data = await response.json();
                if (data.reply) {
                    addMessage(data.reply);
                } else {
                    addMessage('服务暂时不可用');
                }
            } catch (error) {
                addMessage('网络连接异常');
            } finally {
                loading.style.display = 'none';
            }
        }

        // 侧边栏功能
        async function queryOrder() {
            const orderId = prompt('请输入订单编号:');
            if (orderId) {
                try {
                    const response = await fetch(`/api/order/${orderId}/`);
                    const data = await response.json();
                    addMessage(`订单状态：${data.status}<br>物流信息：${data.logistics}`);
                } catch {
                    addMessage('订单查询失败');
                }
            }
        }

        function connectHuman() {
            loading.style.display = 'block';
            setTimeout(() => {
                loading.style.display = 'none';
                addMessage('人工客服小淘将为您服务！');
                addMessage('请问您需要什么帮助？');
            }, 1000);
        }

        // 客服评价功能
        function showRating() {
            // 引导用户进行评价
            addMessage('请您为本次服务进行评价：<br>' +
                '<button class="rating-btn" onclick="submitRating(5)">⭐️⭐️⭐️⭐️⭐️ 非常满意</button><br>' +
                '<button class="rating-btn" onclick="submitRating(4)">⭐️⭐️⭐️⭐️ 满意</button><br>' +
                '<button class="rating-btn" onclick="submitRating(3)">⭐️⭐️⭐️ 一般</button><br>' +
                '<button class="rating-btn" onclick="submitRating(2)">⭐️⭐️ 不满意</button><br>' +
                '<button class="rating-btn" onclick="submitRating(1)">⭐️ 非常不满意</button>');
        }

        // 提交评价
        function submitRating(rating) {
            // 根据评分显示不同的感谢语
            let thankYouMessage;
            switch (rating) {
                case 5:
                    thankYouMessage = '感谢您的五星好评！我们会继续努力为您提供更好的服务！';
                    break;
                case 4:
                    thankYouMessage = '感谢您的评价！我们会继续改进，期待您的下次光临！';
                    break;
                case 3:
                    thankYouMessage = '感谢您的反馈！我们会认真改进，为您提供更好的服务！';
                    break;
                case 2:
                    thankYouMessage = '感谢您的评价！我们会认真反思并改进服务！';
                    break;
                case 1:
                    thankYouMessage = '非常抱歉给您带来不便，我们会尽快改进！';
                    break;
                default:
                    thankYouMessage = '感谢您的评价！';
            }

            // 显示感谢信息
            addMessage(thankYouMessage);
        }

        // 回车发送
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        })


        // 回车发送
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        });
    </script>
</body>
</html>